package org.zcl.consumer;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zcl.entity.CanalBinlogBean;
import org.zcl.entity.UserEntity;
import org.zcl.utils.RedisUtil;

import java.util.List;

/**
 * @Package org.zcl.consumer
 * @PROJECT_NAME: canal
 * @DESCRIPTION:
 * @USER: zhuchenglin
 * @DATE: 2022/3/31 14:41
 */
@Component
@RocketMQMessageListener(topic = "topic2021", consumerGroup = "ConsumerGroup", selectorExpression = "*")
public class CanalConsumer implements RocketMQListener<MessageExt> {

    //过期时间 6分钟
    private final long expireTime = 600L;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onMessage(MessageExt msg) {
        System.out.println("Consumer收到"+new String(msg.getBody()));

        String strLog = new String(msg.getBody());

        CanalBinlogBean binlogBean = JSONObject.parseObject(strLog, CanalBinlogBean.class);

        String type = binlogBean.getType();
        //如果不是ddl语句
        if(!binlogBean.isDdl()){
            String directory = binlogBean.getTable();
            List<UserEntity> list = binlogBean.getData();
            //新增或更新直接set,删除则删除key
            if("INSERT".equals(type) || "UPDATE".equals(type)){
                for (UserEntity data : list) {
                    String key = directory + ":" + data.getId();
                    redisUtil.set(key,JSONObject.toJSONString(data),expireTime);
                }
            }else if ("DELETE".equals(type)) {
                for (UserEntity data : list) {
                    String key = directory + ":" + data.getId();
                    redisUtil.delete(key);
                }
            }
        }
    }
}